import {
  reLaunch,
  showToast,
  hideToast,
  request,
  getStorageSync,
  removeStorage,
  hideLoading,
} from '@tarojs/taro';
import { errorCreate } from './tools';
import { redirectTo } from '@tarojs/router';

/**
 * @description 创建请求实例
 * @param {String}   url -请求地址
 * @param {Object}   data -请求参数
 * @param {Object}   header -添加请求头
 * @param {String}   method -请求类型
 * @returns 请求promise
 */
function createRequest(
  url: string,
  data: object = {},
  header: object = {},
  method?: any,
): Promise<any> {
  const headerDefault = {
    authorization: `${getStorageSync('token')}`,
    'content-Type': 'application/json',
  };

  // 应用版本
  const appEdition = process.env.APP_EDITION;
  // 来源页面
  const fromPage = encodeURIComponent(window.location.hash.replace('#', ''));

  Object.assign(headerDefault, header);
  if (!getStorageSync('token')) headerDefault.authorization = '';

  return new Promise((resolve, reject) => {
    request({
      url,
      data,
      header: headerDefault,
      method,
      success: (res) => {
        hideToast();
        hideLoading();
        if (res.statusCode === 404) {
          console.log('url not found:', url);
        } else if (res.statusCode === 500) {
          redirectTo({
            url: '/pages/common/500/index',
          });
        } else if (res.statusCode === 200) {
          const dataRequest = res.data;
          //部分接口token失效 直接返回空
          if (!dataRequest || !dataRequest.comResp) {
            showToast({
              title: '登陆token失效',
              icon: 'error',
            });
            setTimeout(() => {
              logout(appEdition, fromPage);
            }, 1000);
          } else if (dataRequest.comResp.code === undefined) {
            return dataRequest;
          } else if ([100].includes(dataRequest.comResp.code)) {
            resolve(dataRequest);
          } else if ([117, 101].includes(dataRequest.comResp.code)) {
            //117 判断token是否过期
            //根据token失效时间判断自动进行重新登录
            //不弹提示框
            if (dataRequest.comResp.code === 101) {
              showToast({
                title: dataRequest.comResp.err,
                icon: 'error',
              });
            }
            setTimeout(() => {
              logout(appEdition, fromPage);
            }, 1000);
          } else {
            // 业务警告
            if ([102, 104, 114].includes(dataRequest.comResp.code)) {
              showToast({
                title: dataRequest.comResp.tip || dataRequest.comResp.msg,
                icon: 'error',
              });
            }

            reject(dataRequest as Constants.ComResp);
            errorCreate(dataRequest.comResp.tip || dataRequest.comResp.msg);
          }
        } else {
          console.log('other request network error:', url);
        }
      },
      fail: () => {
        hideLoading();
      },
    });
  });
}

/**
 * token失效登出
 */
function logout(appEdition?: string, fromPage?: string) {
  removeStorage({
    key: 'token',
    success() {
      reLaunch({
        url: `${
          appEdition === 'hgy' ? '/pages/user/dg-work-login/index' : '/pages/user/login/index'
        }?toPage=${fromPage}`,
      });
    },
  });
}

/**
 * @description 创建请求实例(腾讯地图定制请求)
 * @param {String}   url -请求地址
 * @param {Object}   data -请求参数
 * @param {Object}   header -添加请求头
 * @param {String}   method -请求类型
 * @returns 请求promise
 */
function createQQMapRequest(
  url: string,
  data: object = {},
  header: object = {},
  method?: any,
): Promise<any> {
  return new Promise((resolve, reject) => {
    request({
      url,
      data,
      header,
      method,
      jsonp: true,
      success: (res) => {
        const dataRequest = res.data;

        if (dataRequest.status === 0) {
          resolve(dataRequest.result || dataRequest.data);
        } else {
          reject(dataRequest);
          errorCreate(dataRequest.message);
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

export { createRequest, createQQMapRequest };
